package ace.cmp.spring.graphql.core.configurer;

import ace.cmp.spring.graphql.core.helper.TypeDefinitionRegistryHelper;
import graphql.schema.idl.TypeDefinitionRegistry;
import java.util.List;
import java.util.stream.Stream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.graphql.execution.TypeDefinitionConfigurer;

/**
 * @author caspar
 * @date 2023/8/24 15:32 支持特性：
 * 1、合并{@link graphql.language.ObjectTypeDefinition}
 * 2、自动注入到指定类型的字段中
 */
@Slf4j
public class GraphqlSchemaInjectToTypeFieldConfigurer implements TypeDefinitionConfigurer {

  private final List<GraphqlSchemaInjectToTypeField> injectToTypeFields;
  private final TypeDefinitionRegistryHelper registryHelper;

  public GraphqlSchemaInjectToTypeFieldConfigurer(
      List<GraphqlSchemaInjectToTypeField> injectToTypeFields,
      TypeDefinitionRegistryHelper registryHelper) {
    this.injectToTypeFields = injectToTypeFields;
    this.registryHelper = registryHelper;
  }

  @Override
  public void configure(TypeDefinitionRegistry registry) {
    Stream.ofNullable(injectToTypeFields)
        .flatMap(List::stream)
        .forEachOrdered(
            injectToTypeField -> {
              registryHelper.injectToAssignTypeField(
                  registry,
                  injectToTypeField.getInjectToTypeName(),
                  injectToTypeField.getInjectToFieldName(),
                  injectToTypeField.getInjectType());
            });
  }
}
